<template>
  <div>
    <el-card>
      <div slot="header">
        <span>发布资源</span>
      </div>
      <div style="height:100%;">
        <!-- 发布资源步骤条 -->
        <el-steps :space="200" :active="checkoutvalstep-0" finish-status="success" align-center>
          <el-step title="资源封面"></el-step>
          <el-step title="资源标题"></el-step>
          <el-step title="基本信息"></el-step>
          <el-step title="资源内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <!-- 发布资源内容信息 -->
        <el-form label-position="top" class="addarticle_box" :model="addarticleform" :rules="addFormRules" ref="addarticleRefs">
          <el-tabs v-model="checkoutvalstep" tab-position="left" style="min-height: 520px;">
            <el-tab-pane label="资源封面" name="0">
              <div>
                <div class="cropper-content">
                  <div class="cropper">
                    <vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" :fixedBox="option.fixedBox" @realTime="realTime">
                    </vueCropper>
                  </div>
                  <div class="show-preview" :style="{'width': previews.w + 'px', 'height': previews.h + 'px',  'overflow': 'hidden', 'margin': '5px'}">
                    <div :style="previews.div" class="preview">
                      <img :src="previews.url" :style="previews.img">
                    </div>
                  </div>
                </div>

                <div class="footer-btn">
                  <div class="scope-btn">
                    <label class="btn" for="uploads">更换图片</label>
                    <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/jpg" @change="uploadImg($event, 1)">

                    <button @click="changeScale(1)"><i class="el-icon-zoom-in"></i></button>
                    <button @click="changeScale(-1)"><i class="el-icon-zoom-out"></i></button>
                    <button @click="rotateLeft"><i class="el-icon-refresh-right"></i></button>
                    <button @click="rotateRight"><i class="el-icon-refresh-left"></i></button>
                  </div>
                  <div class="upload-btn">
                    <button type="primary" @click="uploadcover">上传<i class="el-icon-upload el-icon--right"></i></button>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="资源标题" name="1">
              <el-form-item label="资源标题：" prop="title">
                <el-input v-model="addarticleform.title" placeholder="请输入所发布资源的标题(2~20字内)"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="基本信息" name="2">
              <el-form-item label="资源分类" prop="category">
                <el-select v-model="addarticleform.category" placeholder="请选择资源分类">
                  <el-option v-for="firstItem in categorieslist" :label="firstItem.title" :value="firstItem._id" :key="firstItem._id">
                    <span style="float: left;padding-left:20px;font-size: 18px"><i :class="firstItem.className"></i></span>
                    <span style="padding-left:60px;font-size: 16px">{{firstItem.title}}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="发布时间" class="article_time" required>
                <el-col :span="9">
                  <el-form-item prop="createAt1">
                    <el-date-picker type="date" placeholder="选择日期" v-model="addarticleform.createAt1" style="width: 100%;"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col class="line" :span="1">-</el-col>
                <el-col :span="9">
                  <el-form-item prop="createAt2">
                    <el-time-picker placeholder="选择时间" v-model="addarticleform.createAt2" style="width: 100%;"></el-time-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="资源内容" name="3">
              <!-- 富文本编辑框 -->
              <div class="editor">
                <div ref="toolbar" class="toolbar">
                </div>
                <div ref="editor" class="text">
                </div>
              </div>
              <!-- 保存按钮 -->
              <el-button type="info" @click='draftart' class="draftbtn">保存为草稿</el-button>
              <!-- 提交按钮 -->
              <el-button type="primary" @click='publishart' class="publishbyn">发布</el-button>
            </el-tab-pane>
            <el-tab-pane label="" name="4">
              <div class="father_box">
                <el-result title="bingo!" subTitle="上传成功">
                  <template slot="icon">
                    <img class="finishart" src="../../assets/imgs/logo-big.png" alt="发布完成">
                  </template>
                  <template slot="extra">
                    <el-button type="text" @click="againart"><i class="el-icon-back"></i>再发布一个</el-button>
                    <el-button type="text" class="right_btn">前往首页<i class="el-icon-right"></i></el-button>
                  </template>
                </el-result>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import Editor from 'wangeditor'
import _ from 'lodash'
export default {
  data() {
    return {
      // 富文本
      editor: '',
      name: '',
      // 步骤条所需数据
      checkoutvalstep: '',
      // 要发布的资源表单
      addarticleform: {
        title: '',
        state: 1,
        content: '',
        category: '',
        thumbnail: '',
        createAt1: '',
        createAt2: ''
      },
      // 表单验证规则
      addFormRules: {
        title: [
          { required: true, message: '请输入资源标题', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择资源分类', trigger: 'change' }
        ],
        createAt1: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        createAt2: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ]
      },
      // 资源分类信息
      categorieslist: [],
      // 封面
      crap: false,
      previews: {},
      option: {
        img: '',
        size: 1,
        full: false, // 输出原图比例截图
        outputType: 'png',
        canMove: true,
        original: false,
        canMoveBox: true,
        autoCrop: true,
        autoCropWidth: 400,
        autoCropHeight: 200,
        fixedBox: true
      }
    }
  },
  created() {
    this.getcategorieslist()
  },
  mounted() {
    const that = this
    // wangeditor
    this.editor = new Editor(this.$refs.toolbar, this.$refs.editor)
    // base 64 存储图片
    this.editor.config.uploadImgShowBase64 = true
    // 配置服务器端地址
    this.editor.config.uploadImgServer = 'http://localhost:3000/upload'
    // 后端接受上传文件的参数名
    this.editor.config.uploadFileName = 'avatar'
    // 将图片大小限制为 2M
    this.editor.config.uploadImgMaxSize = 2 * 1024 * 1024
    // 限制一次最多上传 3 张图片
    this.editor.config.uploadImgMaxLength = 1
    // 设置超时时间
    this.editor.config.uploadImgTimeout = 5 * 1000
    // 配置菜单
    this.editor.config.menus = [
      'head', // 标题
      'bold', // 粗体
      'fontSize', // 字号
      'fontName', // 字体
      'italic', // 斜体
      'underline', // 下划线
      'strikeThrough', // 删除线
      'foreColor', // 文字颜色
      'backColor', // 背景颜色
      'link', // 插入链接
      'list', // 列表
      'justify', // 对齐方式
      'quote', // 引用
      'emoticon', // 表情
      'image', // 插入图片
      'table', // 表格
      'code', // 插入代码
      'undo', // 撤销
      'redo'// 重复
    ]
    // 隐藏菜单栏提示
    this.editor.config.showMenuTooltips = true
    // 菜单栏提示为下标
    this.editor.config.menuTooltipPosition = 'down'
    // 隐藏网络图片功能
    this.editor.config.showLinkImg = false
    // 对复制过来的内容进行过滤
    this.editor.config.pasteIgnoreImg = true
    // 创建富文本编辑器
    this.editor.create()
    // 富文本内容
    this.editor.txt.html()
    // 图片上传的回调函数
    this.editor.config.uploadImgHooks = {
      // 上传图片之前
      before: function(xhr) {
        // console.log('before', xhr)
      },
      // 图片上传并返回了结果，图片插入已成功
      success: function(xhr) {
      },
      // 图片上传并返回了结果，但图片插入时出错了
      fail: function(xhr, editor, resData) {
        // console.log('fail', resData)
      },
      // 上传图片出错，一般为 http 请求的错误
      error: function(xhr, editor, resData) {
        // console.log('error', xhr, resData)
        that.message({
          showClose: true,
          message: '图片上传出错！',
          type: 'error'
        })
      },
      // 上传图片超时
      timeout: function(xhr) {
        // console.log('timeout')
        that.message({
          showClose: true,
          message: '图片上传超时！',
          type: 'error'
        })
      },
      // 图片上传并返回了结果，想要自己把图片插入到编辑器中
      // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
      customInsert: function(insertImgFn, result) {
        // result 即服务端返回的接口
        // console.log('customInsert', result)
        // console.log(result[0])
        // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
        // insertImgFn(result.data[0])
        // const url = '../' + result.data[0]
        const url = 'http://localhost:3000' + result[0].avatar
        insertImgFn(url)
      }
    }
  },
  methods: {
    // 获取资源分类信息
    async getcategorieslist() {
      const res = await this.$http.get('/categories')
      // console.log(res.data)
      this.categorieslist = res.data
    },
    // 修改图片大小
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 实时预览函数
    realTime(data) {
      this.previews = data
    },
    // 保存资源封面
    uploadcover() {
      this.$refs.cropper.getCropData((data) => {
        this.addarticleform.thumbnail = data
        this.$message({
          showClose: true,
          message: '封面保存成功！',
          type: 'success'
        })
      })
    },
    uploadImg(e, num) {
      // 上传图片
      // this.option.img
      const that = this
      var file = e.target.files[0]
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        that.$message({
          showClose: true,
          message: '图片类型必须是.gif,jpeg,jpg,png,bmp中的一种!',
          type: 'error'
        })
        return false
      }
      var reader = new FileReader()
      reader.onload = (e) => {
        let data
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        if (num === 1) {
          this.option.img = data
        } else if (num === 2) {
          this.example2.img = data
        }
      }
      // 转化为base64
      reader.readAsDataURL(file)
      // 转化为blob
      // reader.readAsArrayBuffer(file)
    },
    // 点击保存草稿按钮后发送后台数据事件
    draftart() {
      this.$refs.addarticleRefs.validate(async (valid) => {
        if (!valid) return
        this.addarticleform.content = this.editor.txt.html()
        // this.addarticleform.content = this.editor.txt.text()
        // console.log(this.addarticleform.content)
        const createAt = this.addarticleform.createAt2
        const copyaddForm = _.clone(this.addarticleform)
        delete copyaddForm.createAt1
        delete copyaddForm.createAt2
        copyaddForm.createAt = createAt
        copyaddForm.state = 0
        // console.log(this.addarticleform)
        // console.log(copyaddForm)
        const formdata = this.$qs.stringify(copyaddForm)
        const res = await this.$http({
          method: 'post',
          url: '/posts',
          data: formdata
        })
        // return console.log(res)
        if (res.status !== 200) {
          return this.$message({
            showClose: true,
            message: '资源保存失败！',
            type: 'success'
          })
        }
        this.$message({
          showClose: true,
          message: '资源保存成功！',
          type: 'success'
        })
        this.checkoutvalstep = '4'
      })
    },
    // 点击发布后发送后台数据事件
    publishart() {
      // var data = new FormData()
      // data.append('cotent', this.editor.txt.html())
      // console.log(this.editor.txt.html())
      this.$refs.addarticleRefs.validate(async (valid) => {
        if (!valid) return
        this.addarticleform.content = this.editor.txt.html()
        const createAt = this.addarticleform.createAt2
        const copyaddForm = _.clone(this.addarticleform)
        delete copyaddForm.createAt1
        delete copyaddForm.createAt2
        copyaddForm.createAt = createAt
        // console.log(this.addarticleform)
        // console.log(copyaddForm)
        const formdata = this.$qs.stringify(copyaddForm)
        const res = await this.$http({
          method: 'post',
          url: '/posts',
          data: formdata
        })
        // return console.log(res)
        if (res.status !== 200) {
          return this.$message({
            showClose: true,
            message: '资源发布失败！',
            type: 'success'
          })
        }
        this.$message({
          showClose: true,
          message: '资源发布成功！',
          type: 'success'
        })
        this.checkoutvalstep = '4'
      })
    },
    // 在发布一次
    againart() {
      this.$router.go(0)
    }
  }
}
</script>

<style lang="less" scoped>
.cropper-content{
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
  .cropper{
    width: 550px;
    height: 400px;
  }
  .show-preview{
    flex: 1;
    width: 400px;
    height: 200px;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    .preview{
      overflow: hidden;
      border:1px solid #cccccc;
      background: #cccccc;
      margin-left: 40px;
    }
  }
}

.footer-btn{
  margin-top: 30px;
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
  button {
    border: none;
    height: 40px;
    line-height: 40px;
  }
  .scope-btn{
    font-size: 14px;
    width: 350px;
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    -webkit-justify-content: space-between;
    button {
      width: 40px;
      font-size: 16px;
      border-radius: 3px;
    }
  }
  .upload-btn{
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    button {
      width: 100px;
      margin-left: 230px;
      padding: 0;
      border: 0;
      border-radius: 3px;
      background-color: #67c23a;
      color: #fff;
      font-size: 16px;
    }
  }
  .btn {
    outline: none;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    -webkit-transition: .1s;
    transition: .1s;
    font-size: 16px;
    line-height: 40px;
    padding: 0 30px;
    border-radius: 3px;
    color: #fff;
    background-color: #409EFF;
    border-color: #409EFF;
  }
}

.editor {
    width: 100%;
    margin: 0 auto;
    position: relative;
    z-index: 0;
  .toolbar {
    border: 1px solid #ccc;
  }
  .text {
    border: 1px solid #ccc;
    min-height: 400px;
    margin-bottom: 30px;
  }
}

.draftbtn ,.publishbyn{
  width: 160px;
}

.finishart {
  width: 240px;
  height: 200px;
}

.right_btn {
  margin-left: 240px;
}

.father_box {
  font-size: 16px;
}
</style>
